package com.swz.dcrm.ui.home;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CustomAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.adpter.TodayPlanAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.ClueRecord;
import com.swz.dcrm.model.Page;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CustomerManagementViewModel;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.RxTimer;
import com.swz.dcrm.wrapper.EmptyWrapper;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.widget.DrawableTextView;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;


public class CustomerManagementItemFragment extends BaseFragment {


    @BindView(R.id.tv_condition1)
    DrawableTextView tvCondition1;
    @BindView(R.id.tv_condition2)
    DrawableTextView tvCondition2;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.ll_condition)
    LinearLayout llCondition;
    private ActionSheetDialog condition1Dialog;
    private ActionSheetDialog condition2Dialog;


    private Integer condition1Position;
    private int condition2Position;
    private int page=1;
    private int size=10;
    private int total;

    private TodayPlanAdapter todayPlanAdapter;
    String[] types;
    String type;
    private TimePickerView timePickerView;
    private String time1;
    private String time2;
    private int click;
    private RxTimer rxTimer;
    EmptyWrapper emptyWrapper;
    int status;
    @Inject
    CustomerManagementViewModel customerManagementViewModel;
    @Inject
    MainViewModel mainViewModel;

    public static CustomerManagementItemFragment newInstance(String type) {
        CustomerManagementItemFragment fragment=new CustomerManagementItemFragment();
        Bundle bundle=new Bundle();
        bundle.putString("type",type);
        fragment.setArguments(bundle);
        return fragment;
        // Required empty public constructor
    }
    @Override
    public void onLoadRetry() {

        MediatorLiveData<BaseResponse<Page<ClueRecord>>> mediatorLiveData=null;
        if(type.equals(types[0])){
            status=5;
            mediatorLiveData= customerManagementViewModel.getPotentialClueList(condition1Position,condition2Position,page,size);
        }else if(type.equals(types[1])){
            status=6;
            mediatorLiveData=customerManagementViewModel.getOrderClueList(time1,time2,page,size);
        }else if(type.equals(types[2])) {
            status=7;
            boolean defeatedHasBuyCar=false ;
            if(condition2Position==0){
                defeatedHasBuyCar=false;
            }else if(condition2Position==1){
                defeatedHasBuyCar=true;
            }
            mediatorLiveData=customerManagementViewModel.getDefeatedClueList(condition1Position,defeatedHasBuyCar,page,size);
        }else {
            status=8;
            smartRefreshLayout.setEnableLoadmore(false);
            customerManagementViewModel.getAuthorizedClueList().observe(this,authorizedObserver );
            return;
        }

        if(mediatorLiveData.hasActiveObservers()){
            return;
        }
            mediatorLiveData
                    .observe(this, observer);


    }
    Observer authorizedObserver=new Observer<BaseResponse<List<ClueRecord>>>() {
        @Override
        public void onChanged(BaseResponse<List<ClueRecord>> listBaseResponse) {
            mHolder.showLoadSuccess();
            smartRefreshLayout.finishRefresh();
            if(listBaseResponse.isSuccess()){
                if(todayPlanAdapter==null){
                    todayPlanAdapter=new TodayPlanAdapter(getContext(),listBaseResponse.getData(),R.layout.item_customer,status);
                    todayPlanAdapter.setOnButtonClick(onButtonClick);
                    todayPlanAdapter.setOnClickListener(onClickListener);
                    emptyWrapper=getEmptyWrapper(todayPlanAdapter,R.mipmap.empty_client);
                    rv.setAdapter(emptyWrapper);
                }else {
                    todayPlanAdapter.refresh(1,listBaseResponse.getData());
                    emptyWrapper.notifyDataSetChanged();
                }
            }else if(listBaseResponse.getCode()==10001){

                todayPlanAdapter=new TodayPlanAdapter(getContext(),new ArrayList<>(),R.layout.item_customer,status);
                todayPlanAdapter.setOnButtonClick(onButtonClick);
                todayPlanAdapter.setOnClickListener(onClickListener);
                emptyWrapper=getEmptyWrapper(todayPlanAdapter,R.mipmap.empty_client);
                rv.setAdapter(emptyWrapper);
            }
        }
    };

    Observer<BaseResponse<Page<ClueRecord>>> observer=new Observer<BaseResponse<Page<ClueRecord>>>() {
        @Override
        public void onChanged(BaseResponse<Page<ClueRecord>> pageBaseResponse) {
            if(pageBaseResponse==null){
                return;
            }
            smartRefreshLayout.setEnableLoadmore(true);
            smartRefreshLayout.finishLoadmore();
            smartRefreshLayout.finishRefresh();
            if(pageBaseResponse.isSuccess()){

                mHolder.showLoadSuccess();
                total=pageBaseResponse.getData().getTotal();
                if(todayPlanAdapter==null){
                    todayPlanAdapter=new TodayPlanAdapter(getContext(),pageBaseResponse.getData().getList(),R.layout.item_customer,status);
                    todayPlanAdapter.setOnButtonClick(onButtonClick);
                    todayPlanAdapter.setOnClickListener(onClickListener);
                    emptyWrapper=getEmptyWrapper(todayPlanAdapter,R.mipmap.empty_client);
                    rv.setAdapter(emptyWrapper);
                }else {
                    todayPlanAdapter.refresh(pageBaseResponse.getData().getPageNum(),pageBaseResponse.getData().getList());
                    emptyWrapper.notifyDataSetChanged();
                }

            }
        }
    };

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(rxTimer.isDisposable()){
           page=1;
           onLoadRetry();
           smartRefreshLayout.setEnableLoadmore(true);
        }

    }
    @Override
    public int layoutId() {
        return R.layout.fragment_customer_management_item;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        types=getResources().getStringArray(R.array.customer_management_state);
        type=getArguments().getString("type");


        timePickerView=getTimePickerView((date, v) -> {
              if(click==1){
                  time1=DateUtils.dateFormat(date,"yyyy-MM-dd");
                  tvCondition1.setText(time1);
                  onLoadRetry();
              }else {
                  time2=DateUtils.dateFormat(date,"yyyy-MM-dd");
                  tvCondition2.setText(time2);
                  onLoadRetry();
              }
        }).build();
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.addItemDecoration(new CustomDecoration(getContext(),0,10,10,10));
        if(type.equals(types[0])){
            String[] sort=getResources().getStringArray(R.array.customer_management_condition_sort);
            String[] state=getResources().getStringArray(R.array.customer_management_condition_state);
            tvCondition1.setText(state[0]);
            tvCondition2.setText(sort[0]);
            condition1Dialog=new ActionSheetDialog(getContext(),state,null);
            condition2Dialog=new ActionSheetDialog(getContext(),sort,null);
            condition2Dialog.isTitleShow(false);
            condition1Dialog.isTitleShow(false);
            condition1Dialog.setOnOperItemClickL((parent, view, position, id) -> {
                smartRefreshLayout.setEnableLoadmore(true);
                tvCondition1.setText(state[position]);

                if(position==0){
                    condition1Position=null;
                }else {
                    condition1Position=position-1;
                }
                onLoadRetry();
                condition1Dialog.dismiss();
            });
            condition2Dialog.setOnOperItemClickL((parent, view, position, id) -> {
                smartRefreshLayout.setEnableLoadmore(true);
                tvCondition2.setText(sort[position]);
                condition2Position=position;
                onLoadRetry();
                condition2Dialog.dismiss();
            });
        }else if(type.equals(types[1])){
            tvCondition1.setText("下单日期");
            tvCondition2.setText("交车日期");
        }else if(type.equals(types[2])){
            String[] reason=getResources().getStringArray(R.array.customer_management_condition_reason);
            String[] state=getResources().getStringArray(R.array.customer_management_condition_state);
            tvCondition1.setText(state[0]);
            tvCondition2.setText(reason[0]);
            condition1Dialog=new ActionSheetDialog(getContext(),state,null);
            condition2Dialog=new ActionSheetDialog(getContext(),reason,null);
            condition2Dialog.isTitleShow(false);
            condition1Dialog.isTitleShow(false);
            condition1Dialog.setOnOperItemClickL((parent, view, position, id) -> {
                smartRefreshLayout.setEnableLoadmore(true);
                tvCondition1.setText(state[position]);

                if(position==0){
                    condition1Position=null;
                }else {
                    condition1Position=position-1;
                }
                onLoadRetry();
                condition1Dialog.dismiss();
            });
            condition2Dialog.setOnOperItemClickL((parent, view, position, id) -> {
                smartRefreshLayout.setEnableLoadmore(true);
                tvCondition2.setText(reason[position]);
                condition2Position=position;
                onLoadRetry();
                condition2Dialog.dismiss();
            });
        }else if(type.equals(types[3])){
            llCondition.setVisibility(View.GONE);
        }
        smartRefreshLayout.setOnRefreshListener(refreshlayout -> {
           page=1;
           onLoadRetry();
           smartRefreshLayout.setEnableLoadmore(true);
        });
        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if(todayPlanAdapter!=null&&todayPlanAdapter.getItemCount()>=total){
                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            }else {
                page++;
                onLoadRetry();
            }
        });
        rxTimer=new RxTimer();
        mHolder.showLoadingStatus(GlobalAdapter.LOADING_NOT_NEED_MARGIN);
        rxTimer.timer(400,number -> {
            onLoadRetry();

        });

        return false;
    }

    @OnClick(R.id.tv_condition1)
    public  void condition1(){
        if(type.equals(types[1])){
            click=1;
            timePickerView.show();
        }else {
            condition1Dialog.show();
        }

    }
    @OnClick(R.id.tv_condition2)
    public void condition2(){
        if(type.equals(types[1])){
            click=2;
            timePickerView.show();
        }else {
            condition2Dialog.show();
        }
    }
    private OnClickListener<ClueRecord> onClickListener= clueRecord -> {
        ClueDetailFragmentArgs.Builder builder=new ClueDetailFragmentArgs.Builder();
        builder.setClueId(new Gson().toJson(clueRecord.getBsClueVO().getId()));
        go(null,R.id.action_customerManagementFragment_to_clueDetailFragment,builder.build().toBundle());
    };


    private TodayPlanAdapter.OnButtonClick onButtonClick=new TodayPlanAdapter.OnButtonClick() {

        @Override
        public void onLogging(ClueRecord clueRecord) {
            AddVisitRecordFragmentArgs.Builder builder = new AddVisitRecordFragmentArgs.Builder();
            builder.setClueRecord(new Gson().toJson(clueRecord));
            go(null,R.id.action_todayContactFragment_to_addVisitRecordFragment,builder.build().toBundle());
        }

        @Override
        public void onCall(String phone) {
            mainViewModel.getCall().setValue(phone);
        }

        @Override
        public void onHandUp(long clueId) {

        }
    };





}
